$ (function () {
   let $authuser = $("#form-user");
   let $password = $("#form-password");
   let $login = $(".form-contain")

   //登录逻辑
    $login.submit(function (e) {
        e.preventDefault();

        let sAuthuser = $authuser.val();
        let sPassword = $password.val();

        if (sAuthuser === ""){
            message.showError("用户名不能为空")
            return
        }

        if (sPassword === ""){
            message.showError("密码不能为空")
            return
        }

        let SdataParams = {
            "user_account":sAuthuser,
            "password":sPassword
        };

        $.ajax({
            url:"/users/login/",
            type: "POST",
            data: JSON.stringify(SdataParams),
            // 请求内容的数据类型（前端发给后端的格式）
            contentType: "application/json; charset=utf-8",
            // 响应数据的格式（后端返回给前端的格式）
            dataType: "json",
            async: false
        })
        
            .done(function (res) {
        if (res.errno === "0") {
          // 注册成功
          message.showSuccess('恭喜你，登录成功！');
          setTimeout(function () {
            // 注册成功之后重定向到主页
            window.location.href = document.referrer;
          }, 1000)
        } else {
          // 注册失败，打印错误信息
          message.showError(res.errmsg);
        }
      })
      .fail(function(){
        message.showError('服务器超时，请重试！');
      });
    });

     // get cookie using jQuery
    function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      let cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        let cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }

    function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

  // Setting the token on the AJAX request
    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
      }
    }
  });

});